package com.twu.biblioteca;

public class LibraryNumber {
    private int first;
    private int second;

    public static LibraryNumber parseNumberFromString(String libraryNumber) throws IllegalArgumentException {
        IllegalArgumentException formatException = new IllegalArgumentException("Number format not valid");

        if (libraryNumber.length() != 8 || libraryNumber.indexOf("-") != 3) {
            throw formatException;
        }

        String[] splitSections = libraryNumber.split("-");

        try {
            int first = Integer.parseInt(splitSections[0]);
            int second = Integer.parseInt(splitSections[1]);

            return new LibraryNumber(first, second);
        } catch (NumberFormatException ex) {
            throw formatException;
        }
    }

    public LibraryNumber(int first, int second) {
        if (first < 0 || first > 999) {
            throw new IllegalArgumentException("The first part of the library number needs to be between 0 and 999");
        }

        if (second < 0 || second > 9999) {
            throw new IllegalArgumentException("The second part of the library number needs to be between 0 and 9999");
        }

        this.first = first;
        this.second = second;
    }

    @Override
    public boolean equals(Object other) {
        if (this == other) return true;
        if (this.getClass() != other.getClass()) return false;

        LibraryNumber number = (LibraryNumber) other;
        return this.first == number.first && this.second == number.second;
    }

    @Override
    public String toString() {
        return String.format("%03d-%04d", first, second);
    }
}
